package com.chuangshixinchen.enterprise.entity.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.chuangshixinchen.enterprise.entity.Tb_declaration_flow;
import com.chuangshixinchen.enterprise.service.ITb_declaration_flowService;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StaffInExcelListener extends AnalysisEventListener<StaffInData> {
    private int headNumber = 0;//记录表头行数

    //因为SubjectExcelListener不交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public ITb_declaration_flowService declarationFlowService;
    public Tb_declaration_flow declarationFlow;

    /**
     * 每隔100条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    List<StaffInData> staffInDataExcelList = new ArrayList<StaffInData>();
    public StaffInExcelListener() {}
    public StaffInExcelListener(Tb_declaration_flow declarationFlow, ITb_declaration_flowService declarationFlowService) {
        this.declarationFlowService = declarationFlowService;
        this.declarationFlow = declarationFlow;
    }

    //读取excel内容，一行一行进行读取
    @SneakyThrows
    @Override
    public void invoke(StaffInData staffInData, AnalysisContext analysisContext) {
        if(staffInData == null) {
            throw new Exception("文件数据为空");
        }
        staffInDataExcelList.add(staffInData);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (staffInDataExcelList.size() >= BATCH_COUNT) {
            declarationFlowService.saveStaffIn4Excel(declarationFlow, staffInDataExcelList);
            // 存储完成清理 list
            staffInDataExcelList.clear();
        }


    }
    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

        headNumber++;
        if (headNumber==1){//读取表中标题
            String title = headMap.get(0);
            if (declarationFlow.getDeclarationType()==0){//退工
                if (!title.contentEquals("江苏省用人单位退工停保登记花名册")){
                    throw new ExcelAnalysisStopException();
                }
            }else {//参保
                if (!title.contentEquals("江苏省用人单位用工参保登记花名册")){
                    throw new ExcelAnalysisStopException();
                }
            }
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        declarationFlowService.saveStaffIn4Excel(declarationFlow, staffInDataExcelList);
    }


}